const connection = require('../app/database')

class CommentService{
  // 发表评论
  async create(userId, momentId, content) {
    const statement =  `insert into comment (user_id, moment_id, content) values (?, ?, ?);`
    try {
      const [result] = await connection.execute(statement, [userId, momentId, content])
      return result
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 回复评论
  async reply(userId, momentId, commentId, content) {
    const statement = `insert into comment (user_id, moment_id, comment_id, content) values (?, ?, ?, ?);`
    try {
      const [result] = await connection.execute(statement, [userId, momentId, commentId, content])
      return result
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 修改评论
  async update(commentId, content) {
    const statement = `update comment set content = ? where id = ?`
    try {
      const [result] = await connection.execute(statement, [content, commentId])
      return result
    } catch (error) {
      console.log(error.message)      
      return
    }
  }
  // 删除评论
  async remove(commentId) {
    const statement = `delete from comment where id = ?`
    try {
      const [result] = await connection.execute(statement, [commentId])
      return result
    } catch (error) {
      console.log(error.message)
      return
    }
  }
  // 获取评论列表
  async getListById(momentId) {
    const statement = `
      select c.id id, c.content content, c.moment_id momentId ,c.createAt createAt,
      JSON_OBJECT('id', u.id, 'username', u.username) author
      from comment c
      left join users u 
      on c.user_id = u.id
      where c.moment_id = ?;
    `
    const [result] = await connection.execute(statement, [momentId])
    return result
  }
  // 测试
  async test(usernaem) {
    const statement = `select id from users where username=?;`
    const [result] = await connection.execute(statement, [usernaem])
    console.log(result)
    return result[0]
  }
}

module.exports = new CommentService()